﻿using Comm;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Kinlo.Drv.Drv
{

    public class ElectronicBalanceSocketDrv
    { 
        int PerReadDataLen = 20;
        public string IpAddr;
        public int Port;
        Socket socket;
        public ElectronicBalanceSocketDrv(string ip, int port, int dataLen = 20)
        {
            try
            {
                this.IpAddr = ip;
                this.Port = port;
                this.PerReadDataLen = dataLen;
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.ReceiveTimeout = 500;
                socket.SendTimeout = 500;
                Open();
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("创建电子称 {0},{1} 发生异常 ：", IpAddr, Port, ex.Message)); 
            }
        }
        public bool Connected
        {
            get { return socket.Connected; }
        }
        public void Open()
        {
            try
            {
                socket.Close();
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
                socket.ReceiveTimeout = 500;
                socket.SendTimeout = 500;
                socket.Connect(IpAddr, Port);
                Logger.Info(string.Format("打开电子称 {0},{1}", IpAddr, Port));
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("打开电子称 {0},{1} 发生异常 ：", IpAddr, Port, ex.Message)); 
            }
        }
        public void Disconnect()
        {
            try
            {
                socket.Close();
                Logger.Info(string.Format("关闭电子称{0},{1}", IpAddr, Port));
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("关闭电子称异常 {0},{1} {2}", IpAddr, Port, ex.Message));
            }
        }
        Random rnd = new Random();

        public int FindCRIndex(byte[] bytes)
        {
            var sign = Encoding.Default.GetBytes("\n")[0];
            for (var i = bytes.Length - 1; i > 0; i--)
            {
                if (bytes[i] == sign)
                    return i;
            }
            return -1;
        }

        public byte[] Read()
        {
            try
            {
                var buff = new byte[10240];
                var len = socket.Receive(buff);
                var buff1 = buff.Take(len).ToArray();
                var index = FindCRIndex(buff1);
                var result = buff1.Skip(index - 19).Take(20).ToArray();
               // Console.WriteLine(Encoding.Default.GetString(result));
                return result;
            }
            catch (Exception ex)
            { 
                Logger.Error(string.Format("电子称 {0},{1} 发生异常：{2}", IpAddr, Port, ex.Message),false);
                Open();
                return null;
            }
        }
        public void ClearZero()
        {
            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(IpAddr, Port);
                var b = Encoding.Default.GetBytes("5");
                socket.Send(b);
                socket.Close();
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("电子称:{0},{1} 清零时发生异常:{2}", IpAddr, Port, ex.Message));
            }
        }
    }
}
